package org.nudt.video.service

import org.nudt.common.exception.BadRequestException
import org.nudt.common.model.User
import org.nudt.common.model.dto.UserDto
import org.nudt.common.repository.UserRepository
import org.nudt.common.utils.FileUtil
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.multipart.MultipartFile
import java.util.*

@Service
class UserService(
    private val userRepository: UserRepository,
    @Value("\${file.avatar-path}") private val avatarPath: String,
    @Value("\${file.avatar-max-size}") private val avatarMaxSize: Long,
) {
    
    /**
     * 应用登录
     * @param userDto 用户信息
     * @return 登录后的用户信息
     */
    @Transactional
    fun appLogin(userDto: UserDto): User {
        val user = userRepository.findByAppid(userDto.appid)
        return if (user.isEmpty) {
            val newUser = User(
                username = UUID.randomUUID().toString(),
                nickname = userDto.nickname ?: "Deepseek",
                appid = userDto.appid,
                avatar = "http://192.168.0.177/upload/avatar/default.jpg",
                gender = userDto.gender ?: 0,
                appVersion = userDto.appVersion ?: "",
                osVersion = userDto.osVersion ?: "13",
                deviceName = userDto.deviceName ?: ""
            )
            userRepository.save(newUser)
            newUser
        } else {
            user.get()
        }
    }
    
    /**
     * 更新用户头像
     * @param appid 用户唯一标识
     * @param multipartFile 头像文件
     * @return 更新后的用户信息
     */
    @Transactional(rollbackFor = [Exception::class])
    fun updateAvatar(appid: String, multipartFile: MultipartFile): User {
        // 根据appid查找用户
        val user = userRepository.findByAppid(appid).orElseThrow()
        // 检查文件大小
        FileUtil.checkSize(avatarMaxSize, multipartFile.size)
        // 定义支持的图片格式
        val imageTypes = "jpg png jpeg webp"
        // 获取文件扩展名
        val fileExt = FileUtil.getExtensionName(multipartFile.originalFilename)
        // 检查文件格式
        if (fileExt != null && !imageTypes.contains(fileExt)) {
            throw BadRequestException("文件格式错误！, 仅支持 $imageTypes 格式")
        }
        // 上传文件
        val file = FileUtil.upload(multipartFile, avatarPath)
        // 检查文件是否上传成功
        if (file == null) {
            throw BadRequestException("上传文件出错")
        } else {
            // 更新用户头像
            user.avatar = "http://192.168.0.177/upload/avatar/${file.name}"
            // 保存用户信息
            userRepository.save(user)
            return user
        }
    }
    
    /**
     * 更新用户信息
     * @param appid 用户唯一标识
     * @param nickname 昵称
     * @param gender 性别
     * @param phone 手机号
     * @param email 邮箱
     * @return 更新后的用户信息
     */
    @Transactional(rollbackFor = [Exception::class])
    fun updateUserInfo(appid: String, nickname: String?, gender: Int? = 1): User {
        val user = userRepository.findByAppid(appid).orElseThrow()
        nickname?.apply {
            user.nickname = nickname
        }
        gender.let {
            user.gender = gender
        }
        userRepository.save(user)
        return user
    }
}